package  com.fast.mybatis.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;


//主线更新
public final class StringUtil {

    public static String EMPTY = "";

    /**
     * 判断字符串是否是 空字符串 或者 是null
     * 
     * @param str
     * @return null、""、"null","[]" 返回true，否则false
     */
    public static boolean isEmpty(Object str) {
        if (str == null) {
            return true;
        }
        if (str instanceof String) {
            return str == null || String.valueOf(str).length() == 0
                   || String.valueOf(str).equalsIgnoreCase("null")
                   || str.equals("[]");
        }
       /* if (str instanceof Integer) {
            return Integer.parseInt(String.valueOf(str)) <= 0;
        }*/
        return false;
    }

    /**
     * {@link StringUtil#isEmptyOrNull(String)}取反
     * 
     * @param str
     * @return
     */
    public static boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }

    /**
     * 首字母大写
     * 
     * @param str
     * @return
     */
    public static String toFirstCharUpper(String str) {
        if (StringUtil.isEmpty(str)) {
            return StringUtil.EMPTY;
        }
        char c = str.charAt(0);
        if (Character.isUpperCase(c)) {
            return str;
        }
        StringBuffer sb = new StringBuffer(str);
        sb.setCharAt(0, Character.toUpperCase(c));
        return sb.toString();
    }

    /**
     * 格式化字符串
     * 
     * @param value
     *            字符串中可以存在变量占位符{0}...{n}
     * @param paras
     *            对应占位符的变量值
     * @return
     */
    public static String format(String value, Object... paras) {
        return MessageFormat.format(value, paras);
    }

    public static String replace(String value) {
        String src = new String(value);
        src = replace(src, "*", "//*");
        src = replace(src, "?", "//?");
        src = replace(src, ")", "//)");
        src = replace(src, "(", "//(");
        src = replace(src, "{", "//{");
        src = replace(src, "}", "//}");
        src = replace(src, "|", "//|");
        src = replace(src, "$", "//$");
        src = replace(src, "+", "//+");
        src = replace(src, ".", "//.");
        return src;
    }

    public static String replaceUrl(String value) {
        String src = new String(value);
        src = replace(src, "\r\n", "");
        return src;
    }

    public static String encoderUrl(String value) {
        String src = new String(value);
        src = replace(src, "+", "%2B");
        src = replace(src, "/", "%2F");
        src = replace(src, "=", "%3D");
        return src;
    }

    public static String decoderUrl(String value) {
        String src = new String(value);
        src = replace(src, "%2B", "+");
        src = replace(src, "%2F", "/");
        src = replace(src, "%3D", "=");
        return src;
    }

    public static String xmlReplace(String value) {
        String src = new String(value);
        src = replace(src, "&lt;", "<");
        src = replace(src, "&gt;", ">");
        return src;
    }

    public static String replace(String value, String old, String newChar) {
        return value.replace(old, newChar);
    }

    public static String getKeyBySplit(String split, Object... args) {
        StringBuilder sb = new StringBuilder();

        for (Object arg : args) {
            sb.append(arg);
            sb.append(split);
        }

        int length = sb.length();
        if (length > 0) {
            sb.delete(length - split.length(), length);
        }

        return sb.toString();
    }

    public static String conStringArray(String... array) {
        int size = 0;
        for (String string : array) {
            size += string.length();
        }

        StringBuilder sb = new StringBuilder(size);

        for (String string : array) {
            sb.append(string);
        }

        return sb.toString();
    }

    public static String inputStreamToString(InputStream in) {
        try {
            return IOUtils.toString(in);
        } catch (IOException e) {
            //throw ExceptionWapper.createBapException(e);
            return "";
        }
    }

    public static String arrayConvertString(Object[] arr, String delim) {
        if (arr == null || arr.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i] + delim);
        }
        if (sb.toString().endsWith(delim)) {
            sb.delete(sb.length() - delim.length(), sb.length());
        }
        return sb.toString();
    }

    public static List<String> StringConvertList(String str, String regex) {
        if (isEmpty(str)) {
            return new ArrayList<String>();
        }
        return Arrays.asList(str.split(regex));
    }

    public static String getKey(Object... args) {
        String split = "_";
        StringBuilder sb = new StringBuilder();
        for (Object arg : args) {
            sb.append(arg);
            sb.append(split);
        }

        int length = sb.length();
        if (length > 0) {
            sb.delete(length - split.length(), length);
        }

        return sb.toString();
    }

    public static String getFirstLower(String value) {
        String first = value.substring(0, 1);
        return value.replaceFirst(first, first.toLowerCase());
    }

    public static String getMethod(String value) {
        return "get" + getFirstUpper(value);
    }

    public static String getFirstUpper(String value) {
        String first = value.substring(0, 1);
        return value.replaceFirst(first, first.toUpperCase());
    }

    public static String mapConvertString(Map<String, String> map,
                                          String splite) {
        StringBuffer result = new StringBuffer();
        for (Entry<String, String> entry : map.entrySet()) {
            result.append(entry.getKey() + splite + entry.getValue() + ",");
        }
        if (result.toString().endsWith(",")) {
            result.delete(result.length() - 1, result.length());
        }
        return String.valueOf(result);
    }

    /**
     * 取出一个指定长度大小的随机正整数.
     * 
     * @param length
     *            int 设定所取出随机数的长度。length小于11
     * @return int 返回生成的随机数。
     */
    public static int buildRandom(int length) {
        int num = 1;
        double random = Math.random();
        if (random < 0.1) {
            random = random + 0.1;
        }
        for (int i = 0; i < length; i++) {
            num = num * 10;
        }
        return (int) ((random * num));
    }

    public static String getListStrValue(List<String> list, int index) {

        return String.valueOf(getListValue(list, index));
    }

    public static Double getListDoubleValue(List<String> list, int index) {
        final Object value = getListValue(list, index);
        if (StringUtil.isEmpty(value)) {
            return 0.0;
        }
        return Double.parseDouble(String.valueOf(value));
    }

    public static Integer getListIntValue(List<String> list, int index) {
        final Object value = getListValue(list, index);
        if (StringUtil.isEmpty(value)) {
            return 0;
        }
        return Integer.parseInt(String.valueOf(value));
    }

    public static Object getListValue(List<String> list, int index) {
        if (list == null || list.size() - 1 < index) {
            return "";
        }
        return list.get(index);
    }

    public static String getUpPath(String path) {
        if (StringUtil.isEmpty(path)) {
            return "";
        }
        if (path.lastIndexOf(File.separator) > 0) {
            return path.substring(0, path.lastIndexOf(File.separator));
        } else if (path.lastIndexOf("\\") > 0) {
            return path.substring(0, path.lastIndexOf("\\"));
        } else if (path.lastIndexOf("/") > 0) {
            return path.substring(0, path.lastIndexOf("/"));
        }
        return path;

    }

    public static String getArgs(int index, String... args) {
        if (args == null || args.length <= 0) {
            return "";
        }
        if (args.length > index) {
            return args[index];
        }
        return "";
    }
    
	public static String getColumnName(String column){
		if(column == null){
			return "";
		}
		if(column.indexOf("_") <= 0){
			return column;
		}
		
		List<String> list =Arrays.asList(column.split("_"));
		StringBuilder sb = new StringBuilder(list.get(0));
		for(int i=1;i<list.size();i++){
			sb.append(upperCase(list.get(i)));
		}
		
		return String.valueOf(sb);
	}
	
	public static String lowerCase(String str) {
		if (str == null || str == "") {
			return str;
		}
		char[] ch = str.toCharArray();
		if (ch[0] >= 'A' && ch[0] <= 'Z') {
			ch[0] = (char) (ch[0] + 32);
		}

		return new String(ch);
	}
	
	/**
	 * 功能：将输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	public static String upperCase(String str) {
		if (str == null || str == "") {
			return str;
		}
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}

		return new String(ch);
	}

	 /**
     * <p>
     * Splits the provided text into an array, separators specified. This is an
     * alternative to using StringTokenizer.
     * </p>
     * <p>
     * <p>
     * The separator is not included in the returned String array. Adjacent
     * separators are treated as one separator. For more control over the split
     * use the StrTokenizer class.
     * </p>
     * <p>
     * <p>
     * A {@code null} input String returns {@code null}. A {@code null}
     * separatorChars splits on whitespace.
     * </p>
     * <p>
     * <pre>
     * StringUtils.split(null, *)         = null
     * StringUtils.split("", *)           = []
     * StringUtils.split("abc def", null) = ["abc", "def"]
     * StringUtils.split("abc def", " ")  = ["abc", "def"]
     * StringUtils.split("abc  def", " ") = ["abc", "def"]
     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
     * </pre>
     *
     * @param str            the String to parse, may be null
     * @param separatorChars the characters used as the delimiters, {@code null} splits on
     *                       whitespace
     * @return an array of parsed Strings, {@code null} if null String input
     */
    public static String[] split(final String str, final String separatorChars) {
        List<String> strings = splitWorker(str, separatorChars, -1, false);
        return strings.toArray(new String[strings.size()]);
    }

    /**
     * Performs the logic for the {@code split} and
     * {@code splitPreserveAllTokens} methods that return a maximum array
     * length.
     *
     * @param str               the String to parse, may be {@code null}
     * @param separatorChars    the separate character
     * @param max               the maximum number of elements to include in the array. A zero
     *                          or negative value implies no limit.
     * @param preserveAllTokens if {@code true}, adjacent separators are treated as empty
     *                          token separators; if {@code false}, adjacent separators are
     *                          treated as one separator.
     * @return an array of parsed Strings, {@code null} if null String input
     */
    public static List<String> splitWorker(final String str, final String separatorChars, final int max,
                                           final boolean preserveAllTokens) {
        // Performance tuned for 2.0 (JDK1.4)
        // Direct code is quicker than StringTokenizer.
        // Also, StringTokenizer uses isSpace() not isWhitespace()

        if (str == null) {
            return null;
        }
        final int len = str.length();
        if (len == 0) {
            return Collections.emptyList();
        }
        final List<String> list = new ArrayList<String>();
        int sizePlus1 = 1;
        int i = 0, start = 0;
        boolean match = false;
        boolean lastMatch = false;
        if (separatorChars == null) {
            // Null separator means use whitespace
            while (i < len) {
                if (Character.isWhitespace(str.charAt(i))) {
                    if (match || preserveAllTokens) {
                        lastMatch = true;
                        if (sizePlus1++ == max) {
                            i = len;
                            lastMatch = false;
                        }
                        list.add(str.substring(start, i));
                        match = false;
                    }
                    start = ++i;
                    continue;
                }
                lastMatch = false;
                match = true;
                i++;
            }
        } else if (separatorChars.length() == 1) {
            // Optimise 1 character case
            final char sep = separatorChars.charAt(0);
            while (i < len) {
                if (str.charAt(i) == sep) {
                    if (match || preserveAllTokens) {
                        lastMatch = true;
                        if (sizePlus1++ == max) {
                            i = len;
                            lastMatch = false;
                        }
                        list.add(str.substring(start, i));
                        match = false;
                    }
                    start = ++i;
                    continue;
                }
                lastMatch = false;
                match = true;
                i++;
            }
        } else {
            // standard case
            while (i < len) {
                if (separatorChars.indexOf(str.charAt(i)) >= 0) {
                    if (match || preserveAllTokens) {
                        lastMatch = true;
                        if (sizePlus1++ == max) {
                            i = len;
                            lastMatch = false;
                        }
                        list.add(str.substring(start, i));
                        match = false;
                    }
                    start = ++i;
                    continue;
                }
                lastMatch = false;
                match = true;
                i++;
            }
        }
        if (match || preserveAllTokens && lastMatch) {
            list.add(str.substring(start, i));
        }
        return list;
    }
}
